package com.exrobot.module.rbt.controller.app;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.exrobot.framework.common.pojo.CommonResult;
import com.exrobot.module.rbt.controller.app.vo.MealCodeDeleteVO;
import com.exrobot.module.rbt.controller.app.vo.MealCodeVO;
import com.exrobot.module.rbt.controller.app.vo.MqCommonVO;
import com.exrobot.module.rbt.controller.app.vo.UvlampTaskVO;
import com.exrobot.module.rbt.dal.redis.RbtRedisDAO;
import com.exrobot.module.rbt.enums.MqttTopicPubEnum;
import com.exrobot.module.rbt.enums.MqttTopicSubEnum;
import com.exrobot.module.rbt.service.mqtt.MqttMessageService;
import com.exrobot.module.rbt.service.order.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import jodd.util.StringUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import static com.exrobot.framework.common.pojo.CommonResult.error;
import static com.exrobot.framework.common.pojo.CommonResult.success;

@Tag(name = "APP - MQTT消息推送")
@RestController
@RequestMapping("/mqtt/publish")
@Validated
public class MqttPublishController {

    @Resource
    private MqttMessageService publishService;

    @Resource
    private OrderService orderService;

    @Resource
    private RbtRedisDAO redisDAO;

    /**
     * 发布订餐验证码消息
     */
    @Operation(summary = "APP 发布普通任务")
    @PostMapping("/addOrder")
    @PermitAll
    public CommonResult<String> publishOrder(@RequestBody JSONObject object) {
        String checkCode = redisDAO.generateMealCode();
        object.put("orderType",1);
        object.put("orderSn",redisDAO.generateRobotOrderSn());
        if(!object.containsKey("canteenSn")) {
            object.put("canteenSn",19);
        }
        object.put("code",checkCode);
        object.put("saveCode","00"+checkCode);
        if(!object.containsKey("point")) {
            object.put("area","6:M2");
            object.put("floor","3");
            object.put("point","B");
        } else {
            String[] address = object.get("point").toString().split(":");
            if(address.length != 4) {
               return error(500,"配送点格式错误");
            }
            object.put("area",address[0]+":"+address[1]);
            object.put("floor",address[2]);
            object.put("point",address[3]);
        }
        object.put("mobile","13312341234");
        if(!object.containsKey("items")) {
            JSONArray array = new JSONArray();
            JSONObject item = new JSONObject();
            item.put("menuSn",0);
            item.put("num",1);
            array.add(item);
            object.put("items",array);
        }
        String topic = MqttTopicSubEnum.ORDER_CREATE.getTypeVal();
        MqCommonVO<JSONObject> mqCommonVO = new MqCommonVO<>();
        mqCommonVO.setTs(System.currentTimeMillis());
        mqCommonVO.setValues(object);
        publishMqtt(topic, JSON.toJSONString(mqCommonVO));
        return success(checkCode);
    }

    /**
     * 发布订餐验证码消息
     */
    @Operation(summary = "APP 发布普通任务")
    @PostMapping("/task/{sn}")
    @PermitAll
    public CommonResult<String> publishCommonTask(@RequestBody JSONArray jsonArray, @PathVariable("sn") String sn) {
        String topic = String.format(MqttTopicPubEnum.COMMON_TASK.getTypeVal(), sn);
        MqCommonVO<JSONArray> mqCommonVO = new MqCommonVO<>();
        mqCommonVO.setTs(System.currentTimeMillis());
        mqCommonVO.setValues(jsonArray);
        return publishMqtt(topic, JSON.toJSONString(mqCommonVO));
    }


    /**
     * 发布订餐验证码消息
     */
    @Operation(summary = "APP 发布订餐验证码消息")
    @PostMapping("/meal-code/{sn}")
    @PermitAll
    public CommonResult<String> publishMealCode(@Valid @RequestBody MealCodeVO mealCodeVO,@PathVariable("sn") String sn) {
       String code = mealCodeVO.getCode();
        if(StringUtil.isBlank(code)) {
            code = redisDAO.generateMealCode();
            mealCodeVO.setCode(code);
        }
        MqCommonVO<MealCodeVO> mqCommonVO = new MqCommonVO<>();
        mqCommonVO.setTs(System.currentTimeMillis());
        mqCommonVO.setValues(mealCodeVO);
        String topic = String.format(MqttTopicPubEnum.MEAL_CODE.getTypeVal(), sn);
        CommonResult<String> result = publishMqtt(topic, JSON.toJSONString(mqCommonVO));
        if(result.isError()) {
            return result;
        } else {
            return success(code);
        }
    }
    /**
     * 发布订餐码取消
     */
    @Operation(summary = "APP 发布订餐码取消")
    @PostMapping("/meal-code-delete/{sn}")
    @PermitAll
    public CommonResult<String> publishMealCodeDelete(@Valid @RequestBody MealCodeDeleteVO mealCodeDeleteVO,@PathVariable("sn") String sn) {
        MqCommonVO<MealCodeDeleteVO> mqCommonVO = new MqCommonVO<>();
        mqCommonVO.setTs(System.currentTimeMillis());
        mqCommonVO.setValues(mealCodeDeleteVO);
        String topic = String.format(MqttTopicPubEnum.MEAL_CODE_DELETE.getTypeVal(),sn);
        orderService.updateOrderChange(sn,mealCodeDeleteVO.isAll?null:mealCodeDeleteVO.getCodes());
        return publishMqtt(topic,JSON.toJSONString(mqCommonVO));
    }
    /**
     * 发布紫外灯消息
     */
    @Operation(summary = "APP 发布紫外灯消息")
    @PostMapping("/uvlamp-task/{sn}")
    @PermitAll
    public CommonResult<String> publishUvlampTask(@Valid @RequestBody UvlampTaskVO uvlampTaskVO,@PathVariable("sn") String sn) {
        MqCommonVO<UvlampTaskVO> mqCommonVO = new MqCommonVO<>();
        mqCommonVO.setTs(System.currentTimeMillis());
        mqCommonVO.setValues(uvlampTaskVO);
        String topic = String.format(MqttTopicPubEnum.UVLAMP_TASK.getTypeVal(),sn);
        return publishMqtt(topic,JSON.toJSONString(mqCommonVO));
    }

    @Operation(summary = "APP 发布充电任务消息")
    @PostMapping("/charge-task/{sn}")
    @PermitAll
    public CommonResult<String> publishChargeTask(@PathVariable("sn") String sn) {
        MqCommonVO<Integer> mqCommonVO = new MqCommonVO<>();
        mqCommonVO.setTs(System.currentTimeMillis());
        mqCommonVO.setValues(1);
        String topic = String.format(MqttTopicPubEnum.CHARGE_TASK.getTypeVal(),sn);
        return publishMqtt(topic,JSON.toJSONString(mqCommonVO));
    }

    @Operation(summary = "sendsub")
    @PostMapping("/sendsub/{code}")
    @PermitAll
    public CommonResult<String> sendSub(@PathVariable("code") String code, @RequestBody JSONObject obj) {
        String topic = MqttTopicSubEnum.getVal(code);
        if(StringUtil.isEmpty(topic)) {
            return error(500,"TOPIC为空");
        }
        return publishMqtt(topic,obj.toJSONString());
    }

    @Operation(summary = "sendpub")
    @PostMapping("/sendpub/{code}")
    @PermitAll
    public CommonResult<String> send(@PathVariable("code") String code, @RequestBody JSONObject obj) {
        String topic = MqttTopicPubEnum.getVal(code);
        if(StringUtil.isEmpty(topic)) {
            return error(500,"TOPIC为空");
        }
        return publishMqtt(topic,obj.toJSONString());
    }

    private CommonResult<String> publishMqtt(String topic,String Val) {
        try {
            publishService.sendToMqtt(topic,1,Val);
            return success("消息已成功发布到主题: " + topic);
        } catch (Exception e) {
            return error(500,"消息发布失败到主题: " + topic +",错误：" + e.getMessage());
        }
    }
}
